package com.ideas.impl.mianshi;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lijian.wu
 * @Date 2024/4/17 21:41
 * 两个线程，一个打印奇数，一个打印偶数，然后顺序打印出1-100
 */
public class OddEvenPrinter {

    private static final Lock lock = new ReentrantLock();
    private static final Condition oddCondition = lock.newCondition();
    private static final Condition evenCondition = lock.newCondition();

    private static int number = 1;
    private static final int MAX_NUMBER = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(new OddPrinter());
        Thread evenThread = new Thread(new EvenPrinter());

        oddThread.start();
        evenThread.start();
    }

    //打印奇数
    private static class OddPrinter implements Runnable {

        @Override
        public void run() {
            while (number < MAX_NUMBER){
                lock.lock();
                try {
                    if(number % 2 ==0){
                        oddCondition.await();
                    }
                    System.out.println(number);
                    number++;
                    evenCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        }
    }

    //打印偶数
    private static class EvenPrinter implements Runnable {

        @Override
        public void run() {
            while (number < MAX_NUMBER){
                lock.lock();
                try {
                    if(number % 2 ==1){
                        evenCondition.await();
                    }
                    System.out.println(number);
                    number++;
                    oddCondition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
            }
        }
    }
}
